<?php
/**
 * 《提成信息》实现类
 *
 * @author 孙晓晔
 * @version $Id: Country.class.php 832 2010-01-06 09:17:14Z xuy $
 */

require_once(dirname(__FILE__) . '/FinanceUtil.class.php');

class Commission extends FinanceUtil {
	public $tbl = Constant::tbl_cw_commission;
	
	public $type2 = array(
		'-' => '请选择',
		'1' => '按到帐',
		'2' => '按利润',
		'3' => '按项目',
		
		'9' => '其它',
	);
	
	public $percent = array(
		'-' => '请选择',
		'0.04' => '4%',
		'0.03' => '3%',
		'0.02' => '2%',
		'0.01' => '1%',
		'0.007' => '0.7%',
		'0.005' => '0.5%',
		'0.001' => '0.1%',
	);
	
	public $cost = array(
		'-' => '请选择',
		'1' => '100%',
		'0.9' => '90%',
		'0.85' => '85%',
		'0.8' => '80%',
		'0.75' => '75%',
		'0.7' => '70%',
		'0.6' => '60%',
		'0.5' => '50%',
	);
	
	public $status = array(
		'-' => '请选择',
		'1' => '等待审核',
		'2' => '等待处理',
		'3' => '正在处理',
		'4' => '完成提成',
	
		'5' => '取消提成',

		'9' => '其它',
	);
	
	public $orderby = array(
		'-' => '请选择',
		'customer' => '客户',	
		'date' => '日期',
		'name' => '事由',
		'emp' => '员工',	

		'1' => '创建时间',
		'2' => '更新时间',
	);
	
	public $groupby = array(
		'-' => '请选择',
		'emp' => '员工',
		'type' => '类型',
		'type2' => '提成',
		
		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
		
		$controller->assign_by_ref('type2_option', $this->type2);
		$controller->assign_by_ref('cost_option', $this->cost);
		$controller->assign_by_ref('percent_option', $this->percent);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		// $controller->assign('t1', strtotime('-1 year'));
		
		$controller->display($request, 'finance/commission/find');
		return true;
	}
	
	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == 'mobile') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['mobile'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {		
		$in_item_s = $request['in_item_s'];				
		$name_s = $request['name_s'];
						
		$date1_s = $request['date1_s'];
		$date2_s = $request['date2_s'];

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}
		
		if (!empty($in_item_s)) {
			$where .= $this->_x_s("`in_item`", $in_item_s);
		}
				
		if (!empty($name_s)) {
			$where .= " AND name LIKE '%" . $name_s . "%'";
		}
		
		$where .= $this->_where_x("type", $request['type_s']);
		
		$where .= $this->_where_x("type2", $request['type2_s']);
		$where .= $this->_where_x("percent", $request['percent_s']);
		
		if (!empty($date1_s)) {
			$where .= " AND date >= '" . $date1_s . "'";
		}

		if (!empty($date2_s)) {
			$where .= " AND date < '" . $date2_s . "'";
		}
		
		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}

		$emp = $_SESSION['id'];
		
		$p = array('1'=>'161', '2'=>'162', '3'=>'173');
		
		$a = $this->_audit_office($p);
		if (count($a) > 0) {
			$office = implode(",", $a);
			
			return sprintf(" visible = 1 AND (office in (%s) OR emp = '%s' OR oper = '%s')", $office, $emp, $emp);
		}		

		return sprintf(" visible = 1 AND (emp = '%s' OR oper = '%s')", $emp, $emp);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {
			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		} else {
			$controller->clear_assign('result');
		}

		$controller->display($request, 'finance/commission/list');
		return true;
	}
	
	function _num($id) {
		$ret = $this->_commission($id);
		
		return count($ret);
	}
	
	function _in_item($id, $status = 'all') {
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();
		
		return $aa->_list_transaction($id);
	}
	
	function _in_item_view($id) {
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();
		
		return $aa->_view($id);
	}
	
	function xls($controller, $request) {
		$this->pretreat($controller);
		
		$this->findPara($controller, $request);

		$request['tpl'] = "xls";

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$row = $this->_orderby_x($controller, $row, $this->orderby_s);
			
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'finance/commission/list');
		return true;
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-3 day'));

		$controller->display($request, 'finance/commission/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$in_item = $this->_input($request['in_item']);
		
		$date = $request['date'];
		$customer = $request['customer'];
		
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		
		$currency = $request['currency'];		
		$income = $request['income'];
		
		$cost = $request['cost'];		
		$amount = $request['amount'];
		$profit = $request['profit'];
		
		$type2 = $request['type2'];
		$percent = $request['percent'];
		
		$name = addslashes($request['name']);
		$type = $request['type'];
		$content = addslashes($request['content']);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, name, type, in_item, customer, date, currency, rate, income, rmb, cost, amount, profit, type2, percent, content, emp, oper";
		$fmt .= ", createtime, modifytime) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $office, $name, $type, $in_item, $customer, $date, $currency, $rate, $income, $rmb, $cost, $amount, $profit, $type2, $percent, $content, $emp, $_SESSION['id']);
		debug($sql);
		$db->query($sql);
		
		$request['id_s'] = $db->insert_id();

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/commission/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$in_item = $this->_input($request['in_item']);
		
		$date = $request['date'];
		$customer = $request['customer'];
		
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		
		$currency = $request['currency'];		
		$income = $request['income'];
		
		$cost = $request['cost'];
		$profit = $request['profit'];
		$amount = $request['amount'];
		
		$type2 = $request['type2'];
		$percent = $request['percent'];
		
		$name = addslashes($request['name']);
		$type = $request['type'];
		$content = addslashes($request['content']);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET office = '%s', name = '%s', type = '%s', in_item = '%s', customer = '%s', date = '%s', currency = '%s', rate = '%s', income = '%s', rmb = '%s', cost = '%s', profit = '%s', amount = '%s', ";
		$fmt .= "percent = '%s', type2 = '%s', content = '%s', emp = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $office, $name, $type, $in_item, $customer, $date, $currency, $rate, $income, $rmb, $cost, $profit, $amount, $percent, $type2, $content, $emp, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function copy($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/commission/copy');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {		
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		$controller->assign_by_ref('in_item', $this->_in_item_view($row['in_item']));

		$controller->display($request, 'finance/commission/view');
		return true;
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('310');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '银行到帐';
	
		$cc = array(
			'到帐信息'=>array('w' => "DATE_FORMAT(date, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}
		
		$controller->clear_assign('result');

		$body = $this->_tj_html($controller, $request, 'finance/transaction/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function tjw($controller, $request) {
		$bb = $this->_list_email('310');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '银行到帐（周报）';
	
		$cc = array(
			'到帐信息'=>array('w' => "DATE_FORMAT(date, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE date >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'finance/transaction/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
		
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'currency';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, SUM(amount*rate) AS c, SUM(amount) AS d FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, SUM(amount*rate) AS c, SUM(amount) AS d FROM %s a GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}
	
	function _transaction_item($id, $status = 'all') {
		require_once(dirname(__FILE__) . '/InItem.class.php');
		$aa = new InItem();
		
		return $aa->_list_transaction($id);
	}

	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row['customer_t'] = Name::customer_code($row['customer']);
		
		$row['type_t'] = $this->type[$row['type']];
		$row['type2_t'] = $this->type2[$row['type2']];
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function _list($id, $emp = 'all') {
		$ret = array();
		
		$db = newdb($this->dsn_r);
		if ($emp == 'all' || $emp == '') {
			$fmt = "SELECT * FROM %s WHERE `in_item` = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE `in_item` = '%s' AND emp = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $emp);
		}
		debug($sql);
		$result = $db->query($sql);		
		while ($row = $db->fetch_array($result)) {			
			$row = $this->_view($id, $row);

			$ret[] = $row;
		}
		
		return $ret;
	}
	
	function _list3333($emp) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE emp = '%s' AND status = '3' ORDER BY id";
		$sql = sprintf($fmt, $this->tbl, $emp);
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$row['ok'] = true;			

			$ret[] = $row;
		}

		return $ret;
	}
	
	function _list_3($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE customer = '%s' ORDER BY id DESC LIMIT 20";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$ret[] = $row;
		}
		
		return $ret;
	}
	
	function verify($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/commission/verify');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function verifyPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$content = addslashes($request['content']);
		
		$status = $request['status'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET content = concat(content, '%s'), status = '%s', modifytime = now() WHERE id = %s";
		$sql = sprintf($fmt, $this->tbl, $content, $status, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function finish($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		$row['item'] = $this->_transaction_item($row['id']);

		$controller->assign_by_ref('result', $row);
		
		$email = array(
			'-' => '请选择',
			'1' => '是',		
			'2' => '否',
		);
		$controller->assign_by_ref('email_option', $email);

		$controller->display($request, 'finance/commission/finish');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function finishPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		
		$email = $request['email'];
		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET content = concat(content, '\n%s'), status = '4', modifytime = now() WHERE id = %s";
		$sql = sprintf($fmt, $this->tbl, $content, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}
		
		$row = $this->_view($id);
		if ($email == '1') {			
			$from = $_SESSION['id'];
	
			$to = $row['emp'];
			// $to = "101";
			$row['to'] = Name::emp($to);
			
			// $row['item'] = $this->_transaction_item($row['id']);
	
			$controller->assign_by_ref('result', $row);
			
			$subject = sprintf('提成 %s %s', $row['id'], $row['status_t']);
			$body = $controller->sunxy($request, 'finance/commission/body_4');
			debug($body);
			
			$this->_notice($from, $to, $subject, $body, 1);
		}
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function group($controller, $request) {
		$this->pretreat_group($controller);

		// $controller->assign('t1', strtotime('-3 month'));
		
		$controller->display($request, 'finance/commission/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	function groupby_dd($px) {
		if ($px == '1') {
			return "DATE_FORMAT(date, '%Y-%m-%d %H')";
		}

		if ($px == '2') {
			return "DATE_FORMAT(date, '%Y-%m-%d')";
		}

		if ($px == '3') {
			return "DATE_FORMAT(date, '%Y-%m')";
		}

		return $px;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$fmt = "SELECT %s AS a, SUM(amount) AS c FROM %s a ";
		$sql = sprintf($fmt, $this->s, $this->tbl);

		$where = $this->_where($request);

		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} elseif ($px == 'type') {
			$row['a'] = $this->type[$row['a']];
		} elseif ($px == 'type2') {
			$row['a'] = $this->type2[$row['a']];
		} else {

			$row = $this->_name_t($row, $px);
		}

		return $row;
	}
	
	function z($controller, $request) {

		logdate($controller, $request);
		return true;
	}
		
	function _tj_a($controller, $request) {	
		$s = $this->groupby($controller, $this->groupby_s);
		$df = "DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')";

		$fmt = "SELECT %s as a, SUM(amount) as c FROM %s a WHERE date >= %s GROUP BY %s ORDER BY c DESC";
		$sql = sprintf($fmt, $s, $this->tbl, $df, $s);
		echo $sql . "\n";

		$this->_group_tj($controller, $sql);

		return $controller->sunxy($request, 'tj_a');
	}
}
?>